import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author 管子
 * @date 2025/5/4 10:21
 * @description: TestAQS 类
 */
@Slf4j
public class TestAQS {

    public static void main(String[] args) {
        MyLock lock = new MyLock();
        new Thread(() -> {
            lock.lock();
            try {
                log.info("t1 locking......");
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                log.info("t1 unlocking......");
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                log.info("t2 locking......");
            } finally {
                log.info("t2 unlocking......");
                lock.unlock();
            }
        }, "t2").start();
    }

}

// 自定义的不可重入锁
class MyLock implements Lock {

    // 1：希望实现独占锁 不可重入  则指定实现的方法
    // 同步器类，外面的方法都由它来完成
    class MySync extends AbstractQueuedSynchronizer {
        // 尝试获取锁
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                // 加锁成功，设置独占锁线程为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        // 尝试释放锁
        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == 0 || !isHeldExclusively()) {
                throw new IllegalMonitorStateException();
            }
            // 只有获取锁的线程才能释放锁
            setExclusiveOwnerThread(null);
            setState(0);  // state 是volatile修饰的，可以保证前面的语句对所有线程可见，所以应该把setExclusiveOwnerThread方法放上面
            return true;
        }

        // 是否持有独占锁
        @Override
        protected boolean isHeldExclusively() {
            return isCurrentThread() && getState() == 1;
        }

        public Condition newCondition() {
            return new ConditionObject();
        }

        private boolean isCurrentThread() {
            return getExclusiveOwnerThread().equals(Thread.currentThread());
        }
    }

    private final MySync sync = new MySync();

    // 加锁 (不成功会进入等待队列)
    @Override
    public void lock() {
        sync.acquire(1);
    }

    // 加锁，可打断
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    // 尝试加锁，一次返回结果
    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    // 尝试超时加锁
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    // 解锁
    @Override
    public void unlock() {
        sync.release(1);
    }

    // 生成新的条件队列
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
